package com.hashnode.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.hashnode.cloudservice.PaymentService;
import com.hashnode.model.CommonResult;
import com.hashnode.model.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class CircleBreakerController {
    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

//    @RequestMapping("/payment/get/{id}")
//    @SentinelResource(value = "fallback") //没有配置
////    @SentinelResource(value = "fallback",fallback = "handlExceptionFallback")//异常处理
////    @SentinelResource(value = "fallback",blockHandler = "handleBlockFallback")//处理sentinel控制台配置违规
////    @SentinelResource(value = "fallback",fallback = "handlExceptionFallback",
////            blockHandler = "handleBlockFallback",
////        exceptionsToIgnore = {IllegalArgumentException.class})//两个都配置,如果sentinel有配置熔断规则，则会调用handleBlockFallback,
////    //否则调用handlExceptionFallback，如果设置了exceptionsToIgnore = {IllegalArgumentException.class}则会忽略IllegalArgumentException异常,不走配置的兜底方案
//    public CommonResult<Payment> fallback(@PathVariable Long id)
//    {
//        if (id == 4) {
//            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
//        }
//
//        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/payment/get/"+id,CommonResult.class,id);
//
//        if (result.getData() == null) {
//            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
//        }
//
//        return result;
//    }

    public CommonResult handlExceptionFallback(@PathVariable Long id,Throwable e){
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(444,"兜底异常handlExceptionFallback"+e.getMessage(),payment);
    }

    public CommonResult handleBlockFallback(@PathVariable Long id, BlockException e){
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(445,"兜底Block异常handleBlockFallback"+e.getMessage(),payment);
    }


    @Resource
    private PaymentService paymentService;

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
        //调用paymentService.paymentSQL方法对应的请求
        return paymentService.paymentSQL(id);
    }

}
